<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <h1>{{ UnderLine ? "创建账号" : "欢迎回来" }}</h1>
        <p>{{ UnderLine ? "请注册您的账户继续" : "请登录您的账户继续" }}</p>
      </div>

      <el-form
        :model="form"
        :rules="rules"
        ref="loginForm"
        class="login-form"
        @keyup.enter="submitForm"
      >
        <el-form-item prop="userName">
          <el-input
            v-model="form.userName"
            placeholder="手机号"
            prefix-icon="User"
            size="large"
          />
        </el-form-item>

        <el-form-item prop="passWord">
          <el-input
            v-model="form.passWord"
            placeholder="密码"
            type="password"
            prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>

        <el-form-item prop="validCode" v-if="UnderLine">
          <el-input
            v-model="form.validCode"
            placeholder="验证码"
            type="text"
            prefix-icon="ChromeFilled"
            size="large"
          >
            <template #append>
              <span @click="CodeClick">{{ CodeData.CodeText }}</span>
            </template>
          </el-input>
        </el-form-item>

        <!-- <div class="login-options">
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          <el-link type="primary">忘记密码?</el-link>
        </div> -->

        <el-button
          type="primary"
          size="large"
          class="login-btn"
          :loading="loading"
          @click="submitForm(loginForm)"
        >
          {{ UnderLine ? "注册" : "登录" }}
        </el-button>
      </el-form>

      <div class="login-footer">
        <span>{{ UnderLine ? "已有账号?" : "还没有账号?" }}</span>
        <el-link type="primary" @click="handlechang()">{{
          UnderLine ? "立即登录" : "立即注册"
        }}</el-link>
      </div>
    </div>

    <div class="login-bg"></div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, toRaw } from "vue";
import { useRouter } from "vue-router";
import {
  getCode,
  Authentication,
  login,
  menuPermissions,
} from "../../api/index";

import { useMenuStore } from "../../store/index";

// 表单数据
const form = reactive({
  userName: "",
  passWord: "",
  validCode: "",
});

// 验证码响应式对象
const CodeData = reactive({
  CodeText: "获取验证码",
  time: 60,
});

let isTime = false;
let timer = null;

const CodeClick = () => {
  if (isTime) return;
  // 正则表达式判断是否符合手机号码格式
  const phoneReg =
    /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
  if (!form.userName || !phoneReg.test(form.userName)) {
    return ElMessage({
      message: "请检查你的手机号格式是否正确",
      type: "warning",
    });
  }

  // 清除之前的定时器
  if (timer) clearInterval(timer);

  isTime = true;
  CodeData.time = 60; // 通常验证码有效期60秒
  CodeData.CodeText = `剩余${CodeData.time}s`;

  timer = setInterval(() => {
    CodeData.time -= 1;
    CodeData.CodeText = `剩余${CodeData.time}s`;

    if (CodeData.time <= 0) {
      clearInterval(timer);
      CodeData.CodeText = "获取验证码";
      isTime = false;
    }
  }, 1000);

  getCode({ tel: form.userName }).then(({ data }) => {
    if (data.code === 10000) {
      ElMessage({
        message: data.msg,
        type: "success",
      });
    }
  });
};

// 表单验证规则
const rules = reactive({
  userName: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { min: 11, message: "手机号长度至少11个字符", trigger: "blur" },
  ],
  passWord: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度至少6个字符", trigger: "blur" },
  ],
  validCode: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 4, message: "验证码长度至少4个字符", trigger: "blur" },
  ],
});

const rememberMe = ref(false);
const loading = ref(false);
const loginForm = ref(null);

const UnderLine = ref(0);
const handlechang = () => {
  UnderLine.value = UnderLine.value ? 0 : 1;
};

const router = useRouter();

const useMenuData = useMenuStore();

const routeList = computed(() => {
  return useMenuData.routeList;
});

const submitForm = async (formEl) => {
  if (!formEl) {
    return;
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      // 判断是否是注册或者登录
      if (UnderLine.value) {
        Authentication(form).then(({ data }) => {
          if (data.code === 10000) {
            ElMessage({
              message: "注册成功，请进行登录",
              type: "success",
            });
            UnderLine.value = 0;
            loading.value = false;
          }
        });
      } else {
        login(form).then(({ data }) => {
          if (data.code === 10000) {
            ElMessage({
              message: "登录成功",
              type: "success",
            });
            localStorage.setItem("pz_token", data.data.token);
            localStorage.setItem(
              "pz_userInfo",
              JSON.stringify(data.data.userInfo)
            );
            loading.value = false;
            menuPermissions().then(({ data }) => {
              useMenuData.ChangRouter(data.data);
              toRaw(routeList.value).forEach((item) => {
                router.addRoute("main", item);
              });
              router.push("/");
            });
          }
        });
      }
    } else {
      console.log(fields, "fields");
      return false;
    }
  });
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.login-bg {
  position: absolute;
  top: -50%;
  left: -50%;
  right: -50%;
  bottom: -50%;
  background: linear-gradient(45deg, #e0c3fc, #8ec5fc, #c2e9fb);
  background-size: 400% 400%;
  animation: gradientBG 15s ease infinite;
  z-index: 0;
  opacity: 0.5;
}

@keyframes gradientBG {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

.login-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 420px;
  padding: 40px 35px;
  z-index: 1;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.5);
}

.login-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h1 {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
}

.login-header p {
  color: #7f8c8d;
  font-size: 16px;
}

.login-form {
  margin-bottom: 20px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.login-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;
  background: linear-gradient(45deg, #3498db, #8e44ad);
  border: none;
  transition: all 0.3s;
}

.login-btn:hover {
  transform: scale(1.02);
  box-shadow: 0 5px 15px rgba(52, 152, 219, 0.4);
}

.login-footer {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #eee;
  color: #7f8c8d;
  font-size: 14px;
}

.login-footer span {
  margin-right: 8px;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .login-card {
    padding: 30px 20px;
  }

  .login-header h1 {
    font-size: 24px;
  }
}
</style>